#ifndef CONNECT_CONTEXT_HPP_
#define CONNECT_CONTEXT_HPP_

#include <winsock2.h>
#include <windows.h>
#include "Lock.h"


class Proxy;
class ConnectContext;


class BridgeContext :public WSAOVERLAPPED
{
public:
    BridgeContext(ConnectContext& connectContext, SOCKET& inSocket, SOCKET&  outSocket) ;

    ConnectContext& getConnectContext() {
        return connectContext;
    }

    CHAR* getBuff() {
        return buff;
    }

    size_t getBuffSize() {
        return sizeof(buff);
    }

    enum Operation{IOAccept, IORead, IOWrite};
    Operation complitedOperation;

    int recv();
    int send(DWORD bytesRecv);
    void close();

private:
    void _dbgPrintBuff(DWORD bytesRecv);

    ConnectContext& connectContext;
    SOCKET& _inSocket;
    SOCKET& _outSocket;
    CHAR buff[2048];
};


class ConnectContext
{
public:
    ConnectContext();
    ~ConnectContext();

    bool initialize(HANDLE iocp);
    bool close(BridgeContext* bridge);
    bool waitAccept(SOCKET listenSocket);
    int completeAccept(SOCKET listenSocket, DWORD bytesRecv);


    BridgeContext& getUserToServerBridge() {
        return _userToServerBridge;
    }

    BridgeContext& getServerToUserBridge() {
        return _serverToUserBridge;
    }

private:
    void _close();

    SOCKET _userSocket;
    SOCKET _serverSocket;

    BridgeContext _userToServerBridge;
    BridgeContext _serverToUserBridge;

    int _activeBridgeCount;
};


#endif //CONNECT_CONTEXT_HPP_